<?php
/**
 * Created by PhpStorm.
 * Date: 2021/1/25
 * Time: 12:52 PM
 */
namespace app\common\model;

use think\Model;

class Images extends Model
{
    /**
     * 获取图片资源列表
     * @param $limit
     * @param $where
     * @return array
     */
    public function getImagesList($limit, $where)
    {
        try {

            $list = $this->where($where)->order('img_id desc')->paginate($limit);
            return ['code' => 0, 'data' => $list, 'msg' => 'ok'];
        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /**
     * 插入图片
     * @param $param
     * @return array
     */
    public function addImages($param)
    {
        try {

            $sourceId = $this->insertGetId($param);
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => 0, 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => $sourceId, 'msg' => '上传成功'];
    }

    /**
     * 检测文件是否存在
     * @param $sha1
     * @return array
     */
    public function checkImageExist($sha1)
    {
        try {

            $has = $this->where('sha1', $sha1)->find();
            if (!empty($has)) {
                return ['code' => 203, 'data' => $has, 'msg' => '该图片已经存在了'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => 0, 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => 'success'];
    }

    /**
     * 删除图片
     * @param $imgId
     * @return array
     */
    public function deleteImg($imgId)
    {
        try {

            $this->where('img_id', $imgId)->delete();
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => 0, 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => '删除成功'];
    }

    /**
     * 根据目录获取目录下的全部图片
     * @param $folder
     * @return array
     */
    public function getListByFolder($folder)
    {
        try {
            // TODO 量大可以改为分页
            $list = $this->where('folder', $folder)->select();
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => 0, 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => $list, 'msg' => '获取成功'];
    }
}